<template>
  <div class="page-container-padding page-view">
    <div>
      <el-select v-model="qParams.curCoordination">
        <el-option
          v-for="coor in coordinationList"
          :key="coor.value"
          :value="coor.value"
          :label="coor.name"
        >
          <vab-icon :icon="coor.icon"></vab-icon>
          <span style="margin-left: 10px">
            {{ coor.name }}
          </span>
          <span
            v-show="coor.handleCount > 0"
            style="color: #e74736; float: right"
          >
            {{ coor.handleCount }}
          </span>
        </el-option>
      </el-select>
      <el-select v-model="qParams.state" style="margin-left: 10px">
        <el-option :value="0" label="未处理"></el-option>
        <el-option :value="1" label="已通过"></el-option>
        <el-option :value="2" label="已完成"></el-option>
        <el-option :value="-1" label="已拒绝"></el-option>
      </el-select>
      <el-button
        type="primary"
        icon="el-icon-search"
        style="margin-left: 10px"
        :loading="qParams.qLoading"
        @click="toQuery"
      >
        查询
      </el-button>
    </div>
    <div style="margin-top: 10px">
      <el-table border stripe :data="coordinationRows">
        <el-table-column
          v-if="coordinationRows && coordinationRows.length > 0"
          label="归属ID"
          prop="id"
          width="70"
        />
        <el-table-column
          v-for="col in coordinationColumns"
          :key="col.prop"
          :prop="col.prop"
          :label="col.label"
          :width="col.width"
          show-overflow-tooltip
        />
        <el-table-column
          v-if="coordinationRows && coordinationRows.length > 0"
          label="状态"
          width="70"
        >
          <template #default="{ row }">
            <div
              v-if="row.state < 0"
              class="red"
              @click="toDispatchOrFinish(row)"
            >
              <span>{{ row.state_text }}</span>
              <vab-icon :icon="['fas', 'times']"></vab-icon>
            </div>
            <div
              v-else-if="row.state > 0"
              class="green"
              @click="toDispatchOrFinish(row)"
            >
              <span>{{ row.state_text }}</span>
              <vab-icon :icon="['fas', 'check']"></vab-icon>
            </div>
            <div v-else class="blue" @click="toDispatchOrFinish(row)">
              <span>{{ row.state_text }}</span>
              <vab-icon :icon="['fas', 'edit']"></vab-icon>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        :current-page.sync="qParams.page"
        :page-size="qParams.pageSize"
        layout="total, prev, pager, next, jumper"
        :total="qParams.totalCount"
        @current-change="pageChange"
      />
    </div>
    <el-dialog :visible.sync="magDiag.isShow">
      <div slot="title">
        <span class="red">【{{ magDiag.current.coordinate_name }}】</span>
        {{ magDiag.current.coordinate_title }}
      </div>
      <div style="padding: 10px 15px">
        <el-form
          v-if="magDiag.completeDirectShow"
          :disabled="magDiag.curState !== 0"
        >
          <el-form-item
            v-for="col in magDiag.extraShow"
            :key="col.prop"
            :label="col.label"
          >
            {{ magDiag.current[col.prop] }}
          </el-form-item>
          <el-form-item label="是否接受：">
            <div style="display: flex">
              <el-select v-model="toWorker.row_state" size="mini">
                <el-option :value="1" label="通过" />
                <el-option :value="-1" label="拒绝" />
              </el-select>
              <el-input
                v-show="toWorker.row_state === -1"
                v-model="toWorker.state_plain"
                placeholder="拒绝时可在此填写拒绝的理由"
                size="mini"
                style="margin-left: 4px"
              ></el-input>
            </div>
          </el-form-item>
          <el-form-item v-if="magDiag.current.state < 2" label="选择附件：">
            <div style="display: flex">
              <el-upload
                action="''"
                :before-upload="() => false"
                :multiple="false"
                :on-change="finishAnnexChange"
              >
                <span style="color: #349cfc">
                  <i class="el-icon-upload"></i>
                  点击选择
                </span>
              </el-upload>
              <el-checkbox
                v-model="finishAnnex.is_public"
                style="margin-left: 22px"
              >
                是否外发营业部
              </el-checkbox>
            </div>
          </el-form-item>
          <el-form-item label="资料附件：">
            <span v-if="magDiag.current.annex_url">
              <a :href="magDiag.current.annex_url" target="_blank">
                {{ magDiag.current.annex_name }}
              </a>
              <span v-if="magDiag.current.is_public" style="margin-left: 8px">
                (已外发)
              </span>
            </span>
            <span v-else>
              {{ magDiag.current.annex_name || finishAnnex.annexName }}
            </span>
          </el-form-item>
        </el-form>

        <el-form v-else label-width="70" :disabled="magDiag.curState !== 0">
          <el-form-item
            v-for="col in magDiag.extraShow"
            :key="col.prop"
            :label="col.label"
          >
            {{ magDiag.current[col.prop] }}
          </el-form-item>
          <el-form-item label="是否接受：">
            <div style="display: flex">
              <el-select v-model="toWorker.row_state">
                <el-option :value="1" label="通过" />
                <el-option :value="-1" label="拒绝" />
              </el-select>
              <el-input
                v-show="toWorker.row_state === -1"
                v-model="toWorker.state_plain"
                placeholder="拒绝时可在此填写拒绝的理由"
                style="margin-left: 4px"
              ></el-input>
            </div>
          </el-form-item>
          <el-form-item v-show="magDiag.curState === 0" label="任务分配：">
            <el-select
              v-model="toWorker.worker_id"
              filterable
              clearable
              remote
              placeholder="输入名字搜索"
              :remote-method="getUserByName"
              :loading="toWorker.userLoading"
            >
              <el-option
                v-for="user in toWorker.userList"
                :key="user.id"
                :value="user.id"
                :label="user.admin_name"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer">
        <el-button @click="magDiag.isShow = false">取消</el-button>
        <el-button
          type="primary"
          :loading="magDiag.saveLoading"
          :disabled="magDiag.curState !== 0"
          @click="toSaveDispatchOrFinish"
        >
          确定保存
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import { GetUserListByName } from '@/api/systemManage/userInfo'
  import {
    GetCoordinationManageList,
    DispatchCoordination,
    FinishCoordination,
  } from '@/api/departmentWork/coordination'
  export default {
    data() {
      return {
        coordinationList: [
          {
            value: 'ALL',
            name: '全部',
            icon: 'volleyball-ball',
            handleCount: 0,
          },
        ],
        qParams: {
          curCoordination: 'ALL',
          state: 0,
          page: 1,
          pageSize: 10,
          totalCount: 0,
          qLoading: false,
        },
        coordinationAllCache: [],
        coordinationRows: [],
        coordinationColumns: [],
        magDiag: {
          isShow: false,
          completeDirectShow: false,
          curState: 0,
          coordination: '',
          current: {},
          extraShow: [],
          saveLoading: false,
        },
        toWorker: {
          userLoading: false,
          userList: [],
          worker_id: null,
          record_id: -1,
          row_state: 1,
          state_plain: '',
        },
        finishAnnex: {
          annexName: '',
          annexFile: null,
          is_public: true,
        },
      }
    },
    mounted() {
      this.getRecords()
    },
    methods: {
      getUserByName(name) {
        if (name === '') {
          return
        }
        this.toWorker.userLoading = true
        GetUserListByName(name).then((res) => {
          this.toWorker.userList = res.data
          this.toWorker.userLoading = false
        })
      },
      finishAnnexChange(file) {
        // console.log(file)
        const fileSuffix = file.name.substring(file.name.lastIndexOf('.') + 1)
        if (['pdf', 'doc', 'docx', 'ppt', 'pptx'].indexOf(fileSuffix) < 0) {
          this.$baseMessage('只能上传pdf,docx,pptx类型的文件!', 'error')
          return
        }
        this.finishAnnex.annexFile = file.raw
        this.finishAnnex.annexName = file.name
      },
      getRecords() {
        this.qParams.qLoading = true
        GetCoordinationManageList(
          this.qParams.curCoordination,
          this.qParams.state,
          this.qParams.page,
          this.qParams.pageSize
        )
          .then((res) => {
            console.log(res)
            const resData = res.data
            if (this.qParams.curCoordination === 'ALL') {
              this.coordinationAllCache = resData.rows
              this.qParams.page = 1
              this.showAllCoordinationPage()
              this.coordinationList = resData.coordination
            } else {
              this.coordinationRows = resData.data
            }
            this.coordinationColumns = resData.columns
            this.qParams.totalCount = resData.total_count
            this.qParams.qLoading = false
          })
          .catch(() => {
            this.qParams.qLoading = false
          })
      },
      toQuery() {
        this.qParams.page = 1
        this.getRecords()
      },
      showAllCoordinationPage() {
        const start = (this.qParams.page - 1) * this.qParams.pageSize
        const end = start + this.qParams.pageSize
        this.coordinationRows = this.coordinationAllCache.slice(start, end)
      },

      pageChange(p) {
        this.qParams.page = p
        if (this.qParams.curCoordination === 'ALL') {
          // 使用本地分页
          this.showAllCoordinationPage()
        } else {
          this.getRecords()
        }
      },

      getDiagExtraShow(module) {
        return {
          Lecture: [
            { prop: 'content', label: '内容要求：' },
            { prop: 'link_msg', label: '联系方式：' },
          ],
          Accompany: [{ prop: 'content', label: '内容要求：' }],
          InvestmentPlan: [{ prop: 'content', label: '内容要求：' }],
          Hedging: [
            { prop: 'company_info', label: '公司概况：' },
            { prop: 'content', label: '内容要求：' },
          ],
          CustomerOnline: [
            { prop: 'cycle', label: '交流周期：' },
            { prop: 'content', label: '交流内容：' },
          ],
          AnalysisReport: [{ prop: 'content', label: '报告要求：' }],
          PptCourseware: [{ prop: 'content', label: '课件要求：' }],
          DataNeed: [{ prop: 'content', label: '材料说明：' }],
          WxGroup: [],
          ShouQuan: [
            { prop: 'use_to', label: '申请用途：' },
            { prop: 'apply_notes', label: '申请备注：' },
          ],
        }[module]
      },
      getIsCompelteDirect(module) {
        return {
          WxGroup: true,
          WindRemote: true,
          Ruizhi: true,
          ShouQuan: true,
        }[module]
      },

      toDispatchOrFinish(row) {
        // console.log(row)
        this.magDiag.completeDirectShow = this.getIsCompelteDirect(
          row.coordinate_key
        )
        this.magDiag.curState = row.state // 行原始状态
        this.magDiag.title = row.coordinate_title
        this.magDiag.coordination = row.coordinate_key
        this.magDiag.current = row
        this.magDiag.extraShow = this.getDiagExtraShow(row.coordinate_key)

        this.toWorker.record_id = row.id
        if (row.state === -1) {
          this.toWorker.row_state = -1
          this.toWorker.state_plain = row.state_plain
        }

        this.finishAnnex.annexFile = null
        this.finishAnnex.annexName = ''

        this.magDiag.isShow = true
      },
      toSaveDispatchOrFinish() {
        if (this.magDiag.completeDirectShow) {
          const explainState =
            this.toWorker.row_state === -1 ? this.toWorker.state_plain : ''
          let formData = new FormData()
          formData.append('record_id', this.toWorker.record_id)
          formData.append('state', this.toWorker.row_state)
          formData.append('state_desc', explainState)
          if (this.finishAnnex.annexFile) {
            formData.append('annex', this.finishAnnex.annexFile)
            formData.append('annex_public', this.finishAnnex.is_public)
          }
          this.magDiag.saveLoading = true
          FinishCoordination(this.magDiag.coordination, formData)
            .then((res) => {
              console.log(res)
              this.$baseMessage(res.msg, 'success')
              this.magDiag.saveLoading = false
              this.magDiag.isShow = false
              this.getRecords()
            })
            .catch(() => {
              this.magDiag.saveLoading = false
            })
        } else {
          console.log('dispatch')
          let workerId = this.toWorker.worker_id
          let explainState = ''
          if (this.toWorker.row_state === -1) {
            workerId = 0
            explainState = this.toWorker.state_plain
          } else {
            if (!workerId || workerId === 0) {
              this.$baseMessage('通过申请需分配服务人员!', 'error')
              return
            }
          }
          this.magDiag.saveLoading = true
          DispatchCoordination(this.magDiag.coordination, {
            record_id: this.toWorker.record_id,
            state: this.toWorker.row_state,
            explain_state: explainState,
            worker_id: workerId,
          })
            .then((res) => {
              console.log(res)
              this.$baseMessage(res.msg, 'success')
              this.magDiag.saveLoading = false
              this.magDiag.isShow = false
              this.getRecords()
            })
            .catch(() => {
              this.magDiag.saveLoading = false
            })
        }
      },
    },
  }
</script>
<style scoped lang="scss">
  .page-view {
    .blue {
      color: #409eff;
      cursor: pointer;
    }
    .green {
      color: #0dd068;
      cursor: pointer;
    }
    .red {
      color: #e74736;
      cursor: pointer;
    }
  }
</style>
